package com.bootdo.common.utils;

import com.bootdo.common.annotation.Dict;
import com.bootdo.common.config.DruidDBConfig;
import com.bootdo.common.dict.TailBean;
import com.bootdo.common.domain.DictDO;
import com.bootdo.common.service.DictService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @ClassName DictUtil
 * @Description //TODO
 * @Author 武玉锋
 * @Date 2019-07-29 16:04:
 **/
@Component
public class DictUtil {


    private Logger logger = LoggerFactory.getLogger(DictUtil.class);
    @Autowired
    DictService dictService;

    public void queryEntityAfter(Object  bean) {
        if (bean == null) {
            return;
        }

        if(!(bean instanceof TailBean)){
            logger.error( "指定的pojo"+bean.getClass()+" 不能获取数据字典，需要继承TailBean");
            return;
        }

        TailBean ext  = (TailBean)bean;
        Class c = ext.getClass();
        do {
            Field[] fields = c.getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(Dict.class)) {
                    field.setAccessible(true);
                    Dict dict = field.getAnnotation(Dict.class);

                    try {
                        String display = "";
                        Object fieldValue = field.get(ext);
                        if (fieldValue != null) {
                            DictDO dbDict = dictService.listTypeAndValue(dict.type(),fieldValue.toString());
                            display = dbDict!=null?dbDict.getName():null;
                        }
                        ext.set(field.getName() + dict.suffix(), display);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
            c = c.getSuperclass();
        }while(c!=TailBean.class);

    }

    public void queryListAfter(List list) {
        for (Object bean : list) {
            queryEntityAfter(bean);
        }
    }
}
